import { defineStore } from "pinia";
import { userKey } from "./key"

interface IUserState {
    menus: IMenuData[]
    username: string
}
type menu = IMenuData & { children: IMenuData[] }
export const useUserStore = defineStore(userKey, {
    state(): IUserState {
        return {
            menus: [],
            username: ""
        }
    },
    getters: {
        routes() {
            let menus: menu[] = [];
            // 找到所有的1级
            menus = this.menus
                .filter((item) => item.parentId === 0)
                .map((item) => ({
                    ...item,
                    children: [],
                }));

            // 把2级加入对应的1级的children
            this.menus.forEach((sub) => {
                // 找到 menus 1级里面的id和我的parentId相等的，就我的上级
                const p = menus.find((item) => item.id === sub.parentId);
                // 如果找到了我的上级，加入它的children
                if (p) {
                    p.children.push(sub);
                }
            });
            return menus
        },
        permission(): string[] {
            return this.menus.map((item) => item.name)
        }
    }
})